<template>
  <div class="main">
    <ElCard>
      <template #header>用户登入</template>
      <div>
        <ElForm :model="user" ref="myform" :rules="rules">
          <ElFormItem prop="username">
            <ElInput v-model="user.username" placeholder="登入名"></ElInput>
          </ElFormItem>
          <ElFormItem prop="password">
            <ElInput :show-password="true" v-model="user.password" placeholder="密码"></ElInput>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="login(myform)">登入</ElButton>
            <ElButton type="danger" @click="reset(myform)">重置</ElButton>
          </ElFormItem>
        </ElForm>
      </div>
    </ElCard>
  </div>
</template>

<script lang="ts" setup>
//路由部分
import { useRouter } from 'vue-router'
const router=useRouter();
//状态管理部分
import store from '../../store/index'
const {updateUserInfo} = store()
import { reactive, ref } from 'vue'
import { TbUser, TbUserInfo, UserOtherInfo } from '../../ts/UserInfo'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { ApiService } from '../../ts/ApiService'
import { BaseResult } from '../../ts/BaseResult'
import Tools from '../../ts/Tools'

const user = ref(new TbUser())
const myform = ref<FormInstance>()
const checkUsername = (rule: any, value: string, cb: any) => {
  console.log(rule)
  if (/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/.test(value)) {
    cb()
  } else {
    cb(new Error('用户名开头必须字母开头，且长度是4-15位'))
  }
}

// 校验规则定义
const rules = reactive<FormRules>({
  username: [{ required: true, message: '账号必须填写' }, { validator: checkUsername }],
  password: [{ required: true, message: '密码必须填写' }],
})

function login(myform: FormInstance | undefined) {
  myform.validate((valid) => {
    console.log('表单校验结果', valid)
    if (valid) {
      user.value.password = Tools.md5(user.value.password)
      ApiService.post('/user/auth/login',user.value,(data:BaseResult)=>{
        if(data.success){
          //获取用户信息
          updateUserInfo(()=>{
            
              ElMessageBox.alert(data.message).then(()=>{
            router.push('/user/main')
          })

          })
        
        }
      })
    }
  })
}

function reset(myform: FormInstance) {
  myform.resetFields()
}
</script>

<style lang="scss" scoped>
.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  > div {
    transform: translateY(-10vh);
    min-width: 40%;
  }
}
</style>
